package br.com.j7.jdesk.ui.bean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import br.com.j7.jdesk.persistence.entity.Products;
import br.com.j7.jdesk.persistence.repository.ProductRepository;
import br.com.j7.jdesk.persistence.repository.impl.ProductRepositoryImpl;

/**
 * 
 * 
 * 
 * @author Edivando Alves
 *
 */
@ManagedBean
@RequestScoped
public class ProductBean extends WebContext implements Bean{
	
	private Products product = new Products();
	private List<Products> products;
	private ProductRepository repository = new ProductRepositoryImpl();
	
	public ProductBean() {
		repository = new ProductRepositoryImpl();
	}
	
	@Override
	public String adicionar() {
		try {
			product.setEnterprise(getSessionEnterprise());
			if( product.getIdProduct() == null || product.getIdProduct().equals(0) ){
				product.setIdProduct(null);
				repository.add(product);
				addMessage("ui.mobile.product.add", product.getCdProduct());
			}else {
				addMessage("ui.mobile.product.update", product.getCdProduct());
				repository.update(product);
			}
			product = new Products();
			products = null;
			return "product";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String remover() {
		try {
			if( repository.remove(product) ){
				addMessage("ui.mobile.product.remove", product.getCdProduct());
				products = null;
				product = null;
			}
			return "product";
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<Products> getProducts() {
		try {
			if(products == null){
				products = repository.listByEnterprise(getSessionEnterprise());
			}
			return products;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}
	
	public Products getProduct() {
		return product;
	}
	
	public void setProduct(Products product) {
		this.product = product;
	}
	
	@Override
	public String toForm() {
		return "productForm";
	}
	
	@Override
	public String toList() {
		product = new Products();
		return "product";
	}
	
}
